#include <stdio.h>
#include <string.h>
#include "encode.h"
#include "decode.h"

#define JWT_SECRET_KEY "caoyanglaoshizhenniubi"
#define JWT_SECRET_KEY_LEN (sizeof(JWT_SECRET_KEY) - 1)
#define JWT_ISSUER   "KwanBunCloudServer"
#define JWT_AUDIENCE "KwanBunCloudClient"

int main() {
    // 1. 生成 Token
    struct l8w8jwt_encoding_params params;
    l8w8jwt_encoding_params_init(&params);

    params.alg = L8W8JWT_ALG_HS512;
    params.sub = (char *)"test_user";
    params.iss = (char *)JWT_ISSUER;
    params.aud = (char *)JWT_AUDIENCE;

    params.iat = l8w8jwt_time(NULL);
    params.exp = params.iat + 600; // 10分钟

    params.secret_key = (unsigned char *)JWT_SECRET_KEY;
    params.secret_key_length = JWT_SECRET_KEY_LEN;

    char *jwt = NULL;
    size_t jwt_len = 0;
    params.out = &jwt;
    params.out_length = &jwt_len;

    int r = l8w8jwt_encode(&params);
    if (r != L8W8JWT_SUCCESS || jwt == NULL) {
        printf("Token 生成失败\n");
        return 1;
    }
    printf("生成的TOKEN: %s\n", jwt);

    // 2. 校验 Token
    struct l8w8jwt_decoding_params dparams;
    l8w8jwt_decoding_params_init(&dparams);

    dparams.alg = L8W8JWT_ALG_HS512;
    dparams.jwt = jwt;
    dparams.jwt_length = strlen(jwt);
    dparams.verification_key = (unsigned char *)JWT_SECRET_KEY;
    dparams.verification_key_length = JWT_SECRET_KEY_LEN;
    dparams.validate_iss = (char *)JWT_ISSUER;
    dparams.validate_aud = (char *)JWT_AUDIENCE;
    dparams.validate_sub = (char *)"test_user";
    dparams.validate_exp = 1;
    dparams.exp_tolerance_seconds = 60;
    dparams.validate_iat = 1;
    dparams.iat_tolerance_seconds = 60;

    enum l8w8jwt_validation_result validation_result;
    int decode_result = l8w8jwt_decode(&dparams, &validation_result, NULL, NULL);

    if (decode_result == L8W8JWT_SUCCESS && validation_result == L8W8JWT_VALID) {
        printf("Token 校验成功！\n");
    } else {
        printf("Token 校验失败\n");
    }

    l8w8jwt_free(jwt);
    return 0;
}
